<template>
  <div class="login-container" v-loading.fullscreen.lock="fullscreenLoading">
    <!-- 背景装饰元素 -->
    <div class="government-bg-elements">
      <div class="bg-element-1"></div>
      <div class="bg-element-2"></div>
      <div class="bg-element-3"></div>
    </div>

    <!-- 主登录区域 -->
    <div class="login-main">
      <!-- 左侧信息区域 -->
      <div class="login-info">
        <div class="info-content">
          <div class="government-logo">
            <div class="logo-text">
              <div class="system-name">“居民身后一件事”数据平台</div>
            </div>
          </div>

          <div class="feature-list">
            <div class="feature-item">
              <div class="feature-icon">
                <svg-icon icon-class="secure" />
              </div>
              <span>数据汇聚 · 智能核验</span>
            </div>
            <div class="feature-item">
              <div class="feature-icon">
                <svg-icon icon-class="efficient" />
              </div>
              <span>信息共享 · 安全脱敏</span>
            </div>
            <div class="feature-item">
              <div class="feature-icon">
                <svg-icon icon-class="service" />
              </div>
              <span>业务支撑 · 精准服务</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧登录表单 -->
      <div class="login-form-wrapper">
        <div class="form-container">
          <div class="form-header">
            <h3>用户登录</h3>
            <div class="header-line"></div>
          </div>

          <el-form
            ref="loginForm"
            :model="loginForm"
            :rules="loginRules"
            class="government-form"
            size="medium"
          >
            <!-- <el-form-item prop="username">
              <div class="form-item-label">用户名</div>
              <el-input
                v-model="loginForm.username"
                type="text"
                auto-complete="off"
                placeholder="请输入用户名"
                class="government-input"
              >
                <template #prefix>
                  <svg-icon icon-class="user" class="input-icon" />
                </template>
              </el-input>
            </el-form-item>

            <el-form-item prop="password">
              <div class="form-item-label">密码</div>
              <el-input
                v-model="loginForm.password"
                type="password"
                auto-complete="off"
                placeholder="请输入密码"
                @keyup.enter.native="handleLogin"
                class="government-input"
                show-password
              >
                <template #prefix>
                  <svg-icon icon-class="password" class="input-icon" />
                </template>
              </el-input>
            </el-form-item>

            <el-form-item prop="code" v-if="captchaEnabled">
              <div class="form-item-label">验证码</div>
              <div class="captcha-wrapper">
                <el-input
                  v-model="loginForm.code"
                  auto-complete="off"
                  placeholder="请输入验证码"
                  @keyup.enter.native="handleLogin"
                  class="captcha-input"
                >
                  <template #prefix>
                    <svg-icon icon-class="validCode" class="input-icon" />
                  </template>
                </el-input>
                <div class="captcha-img" @click="getCode">
                  <img :src="codeUrl" alt="验证码" class="captcha-image" />
                  <div class="captcha-refresh">
                    <svg-icon icon-class="refresh" />
                  </div>
                </div>
              </div>
            </el-form-item> -->

            <!-- <div class="form-options">
              <el-checkbox v-model="loginForm.rememberMe" class="remember-me">
                记住密码
              </el-checkbox>
            </div> -->

            <el-form-item>
              <el-button
                :loading="loading"
                type="primary"
                class="login-button"
                v-if="isLogin != 3"
              >
                <!-- @click.native.prevent="handleLogin" -->
                <span v-if="isLogin == 1">
                  <span class="loading-text">系统登录中</span>
                  <span class="loading-dots">...</span>
                </span>
                <span v-else-if="isLogin == 2"> 登 录 成 功</span>
              </el-button>
              <el-button
                :loading="loading"
                type="primary"
                class="login-button"
                style="
                  background: linear-gradient(135deg, #c65023 0%, #9c2f14 100%);
                "
                v-if="isLogin == 3"
              >
                <!-- @click.native.prevent="handleLogin" -->
                <span> {{ errormsg }}</span>
              </el-button>
            </el-form-item>
          </el-form>

          <div class="form-footer">
            <div class="footer-links">
              <!--              <span>还没有账号？</span>-->
              <!--              <a href="#" class="link-text" v-if="register">立即注册</a>-->
            </div>
            <div class="security-tips">
              <svg-icon icon-class="security" class="security-icon" />
              <span>主办单位 聊城市茌平区大数据中心</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 页面底部 -->
    <!--    <div class="government-footer">-->
    <!--      <div class="footer-content">-->
    <!--        <div class="copyright">-->
    <!--          <p>Copyright © 2025 山东云尚大数据有限公司 版权所有</p>-->
    <!--        </div>-->
    <!--      </div>-->
    <!--    </div>-->
  </div>
</template>

<script>
import { getCodeImg, loginSdt } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { Loading } from "element-ui";
import { Message } from 'element-ui'

export default {
  name: "Login",
  data() {
    return {
      codeUrl: "",
      loginForm: {
        username: "",
        password: "",
        rememberMe: false,
        code: "",
        uuid: "",
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" },
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" },
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }],
      },
      loading: false,
      captchaEnabled: true,
      register: false,
      redirect: undefined,
      isLogin: 1,
      resCode: null,
      errormsg: null,
      fullscreenLoading: false,
      loadingInstance: null,
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  created() {
    //山东通直接登录
    //判断当前环境
    this.getLoginPage();
  },
  methods: {
    async getLoginPage() {
      console.log("1. 方法开始执行");
      this.loadingInstance = Loading.service({
        lock: true,
        text: "页面加载中...",
        background: "rgba(0, 0, 0, 0.7)",
      });

      const code = await this.getCode();
      console.log("3. 获取到 code:", code);

      // 添加调试信息
      console.log("localStorage vuex_jump:", sessionStorage.getItem("vuex_jump"));
      console.log("this.$store.state.user.jump:", this.$store.state.user.jump);
      // try {
        if (this.$store.state.user.jump) {
          console.log("使用已有的 jump 状态执行 loginSdt");
          Message.error(err)("请退出重新登录！")
          this.errormsg = "请退出重新登录！"
        } else if (code) {
          // 修复：使用正确的 mutation 提交方式
          this.$store.commit("SET_JUMP", true); // 直接提交到根 mutation
          // 或者如果使用了命名空间：
          // this.$store.commit('user/SET_JUMP', true);

          console.log("4. 执行 loginSdt");
          await this.loginSdt();
          console.log("设置后 jump 状态:", this.$store.state.user.jump);
        } else {
          console.log("5. 跳转到本地路由");
          this.$router.push("/local");
        }
          if (this.loadingInstance) {
          this.loadingInstance.close();
        }
      // } catch {
      //   console.log("登录错误");
      // } finally {
      //   if (this.loadingInstance) {
      //     this.loadingInstance.close();
      //   }
      // }
    },

    loginSdt() {
      const code = this.getCode();
      this.$store
        .dispatch("LoginSdt", code)
        .then((res) => {
          this.resCode = res.code;
          if (res.code == 200) {
            console.log("登陆成功，即将跳转页面");
            this.isLogin = 2;
          } else {
            this.isLogin = 3;
            this.errormsg = res.msg;
            // 修复：使用正确的 mutation 提交方式
            this.$store.commit("SET_JUMP", false);
          }
        })
        .then(() => {
          if (this.resCode == 200) {
            this.$router.push({ path: "/" }).catch(() => {});
          }
        });
    },
    getCode() {
      try {
        const searchParams = new URLSearchParams(window.location.search);
        const redirect = searchParams.get("redirect");
        if (redirect) {
          const decodedRedirect = decodeURIComponent(redirect);
          const code = new URLSearchParams(decodedRedirect.split("?")[1]).get(
            "code"
          );
          return code;
        }
      } catch (error) {
        console.error("获取 code 失败:", error);
      }
      return null;
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get("rememberMe");
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password:
          password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
      };
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), {
              expires: 30,
            });
            Cookies.set("rememberMe", this.loginForm.rememberMe, {
              expires: 30,
            });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove("rememberMe");
          }
          this.$store
            .dispatch("Login", this.loginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || "/" }).catch(() => {});
            })
            .catch(() => {
              this.loading = false;
              if (this.captchaEnabled) {
                this.getCode();
              }
            });
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  //background: linear-gradient(135deg, #1a5f96 0%, #2c3e50 100%);
  background-image: url("../assets/images/img_4.png");
  background-repeat: no-repeat;
  background-size: cover;
  position: relative;
  overflow: hidden;
}

.government-bg-elements {
  position: absolute;
  width: 100%;
  height: 100%;
  pointer-events: none;

  .bg-element-1 {
    position: absolute;
    top: 10%;
    left: 5%;
    width: 200px;
    height: 200px;
    //border: 2px solid rgba(255, 255, 255, 0.1);
    border-radius: 50%;
  }

  .bg-element-2 {
    position: absolute;
    bottom: 15%;
    right: 8%;
    width: 150px;
    height: 150px;
    border: 2px solid rgba(255, 255, 255, 0.08);
    transform: rotate(45deg);
  }

  .bg-element-3 {
    position: absolute;
    top: 50%;
    left: 70%;
    width: 100px;
    height: 100px;
    border: 1px solid rgba(255, 255, 255, 0.05);
    border-radius: 20px;
  }
}

.login-main {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  z-index: 1;
}

.login-info {
  flex: 1;
  max-width: 500px;
  margin-right: 80px;
  color: white;
}

.info-content {
  .government-logo {
    display: flex;
    align-items: center;
    margin-bottom: 20px;

    .logo-icon {
      width: 60px;
      height: 60px;
      background: rgba(255, 255, 255, 0.1);
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 15px;
      backdrop-filter: blur(10px);

      .logo-svg {
        font-size: 32px;
        color: white;
      }
    }

    .logo-text {
      .department {
        font-size: 60px;
        font-weight: 400;
        margin-bottom: 5px;
        opacity: 0.9;
      }

      .system-name {
        margin-left: -250px;
        font-size: 60px;
        font-weight: 600;
        letter-spacing: 1px;
      }
    }
  }

  .welcome-text {
    margin-bottom: 40px;

    h2 {
      font-size: 60px;
      font-weight: 400;
      margin-bottom: 10px;
      letter-spacing: 2px;
    }

    p {
      font-size: 50px;
      opacity: 0.8;
      font-weight: 300;
    }
  }

  .feature-list {
    margin-top: 80px;
    margin-left: -80px;
    .feature-item {
      display: flex;
      align-items: center;
      margin-bottom: 20px;
      font-size: 36px;

      .feature-icon {
        width: 24px;
        height: 24px;
        margin-right: 12px;
        display: flex;
        align-items: center;
        justify-content: center;

        :deep(.svg-icon) {
          font-size: 18px;
          //color: rgba(255, 255, 255, 0.8);
        }
      }
    }
  }
}

.login-form-wrapper {
  background: white;
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  margin-left: 100px;
}

.form-container {
  width: 420px;
  padding: 40px;
}

.form-header {
  text-align: center;
  margin-bottom: 40px;

  h3 {
    font-size: 24px;
    font-weight: 600;
    //color: #2c3e50;
    margin-bottom: 15px;
  }

  .header-line {
    width: 60px;
    height: 3px;
    background: linear-gradient(90deg, #1a5f96, #3498db);
    margin: 0 auto;
    border-radius: 2px;
  }
}

.government-form {
  .form-item-label {
    font-size: 14px;
    //color: #5a6c7d;
    margin-bottom: 8px;
    font-weight: 500;
  }

  .government-input {
    :deep(.el-input__inner) {
      height: 48px;
      border-radius: 8px;
      border: 1px solid #e1e8f0;
      background: #f8fafc;
      transition: all 0.3s ease;

      &:focus {
        border-color: #1a5f96;
        box-shadow: 0 0 0 2px rgba(26, 95, 150, 0.1);
      }
    }

    .input-icon {
      color: #a0aec0;
    }
  }

  .captcha-wrapper {
    display: flex;
    gap: 12px;

    .captcha-input {
      flex: 1;
    }

    .captcha-img {
      position: relative;
      cursor: pointer;
      border-radius: 8px;
      overflow: hidden;
      border: 1px solid #e1e8f0;

      .captcha-image {
        height: 48px;
        display: block;
      }

      .captcha-refresh {
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        width: 30px;
        background: rgba(0, 0, 0, 0.1);
        display: flex;
        align-items: center;
        justify-content: center;

        :deep(.svg-icon) {
          color: white;
          font-size: 14px;
        }
      }
    }
  }
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;

  .remember-me {
    :deep(.el-checkbox__label) {
      color: #5a6c7d;
    }
  }

  .forgot-password {
    .link-text {
      color: #1a5f96;
      text-decoration: none;
      font-size: 14px;

      &:hover {
        text-decoration: underline;
      }
    }
  }
}

.login-button {
  width: 100%;
  height: 48px;
  border-radius: 8px;
  background: linear-gradient(135deg, #237ec6 0%, #14589c 100%);
  border: none;
  font-size: 16px;
  font-weight: 500;
  letter-spacing: 1px;

  // &:hover {
  //   background: linear-gradient(135deg, #164d7a 0%, #243342 100%);
  //   transform: translateY(-1px);
  //   box-shadow: 0 4px 12px rgba(26, 95, 150, 0.3);
  // }

  .loading-text {
    letter-spacing: 0;
  }

  .loading-dots {
    animation: loadingDots 1.5s infinite;
  }
}

@keyframes loadingDots {
  0%,
  20% {
    opacity: 0;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

.form-footer {
  margin-top: 30px;
  text-align: center;

  .footer-links {
    margin-bottom: 20px;

    .link-text {
      color: #1a5f96;
      text-decoration: none;
      font-weight: 500;

      &:hover {
        text-decoration: underline;
      }
    }
  }

  .security-tips {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    color: #303133;

    .security-icon {
      margin-right: 6px;
      font-size: 14px;
    }
  }
}

.government-footer {
  background: rgba(0, 0, 0, 0.2);
  backdrop-filter: blur(10px);
  color: white;
  padding: 20px 0;

  .footer-content {
    max-width: 1200px;
    margin: 0 auto;
    text-align: center;

    .footer-links {
      margin-bottom: 10px;

      a {
        //color: rgba(255, 255, 255, 0.8);
        text-decoration: none;
        font-size: 14px;

        &:hover {
          color: white;
        }
      }

      .divider {
        margin: 0 15px;
        //color: rgba(255, 255, 255, 0.4);
      }
    }

    .copyright {
      p {
        margin: 2px 0;
        font-size: 12px;
        //color: rgba(255, 255, 255, 0.6);
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .login-main {
    flex-direction: column;
    padding: 20px;
  }

  .login-info {
    margin-right: 0;
    margin-bottom: 20px;
    text-align: center;
    max-width: 100%;
  }

  .government-logo {
    justify-content: center;
  }

  .form-container {
    width: 100%;
    max-width: 400px;
    padding: 30px 25px;
  }
}

@media (max-width: 480px) {
  .form-container {
    padding: 25px 20px;
  }

  .captcha-wrapper {
    flex-direction: column;

    .captcha-img {
      width: 100%;

      .captcha-image {
        width: 100%;
        height: 44px;
      }
    }
  }
}
</style>
